package com.lzh.shellcommand.commands

import org.jline.utils.InputStreamReader
import java.io.BufferedReader
import java.lang.management.ManagementFactory
import java.lang.management.MemoryMXBean
import java.lang.management.RuntimeMXBean
import javax.management.remote.JMXConnector
import kotlin.streams.toList


fun String.command(): Process {
    val runtime = Runtime.getRuntime()
    val osName = System.getProperty("os.name")
    return when {
        osName.startsWith("Mac OS") -> {
            runtime.exec(arrayOf("/bin/sh", "-c", this))
        }
        osName.startsWith("Windows") -> {
            throw IllegalStateException("Unsupported Os")
        }
        else -> {
            runtime.exec(arrayOf("/bin/sh", "-c", this))
        }
    }
}

fun Process.lines(): List<String> {
    val reader = BufferedReader(InputStreamReader(this.inputStream))
    return reader.lines().toList()
}

fun JMXConnector.mmxb(): MemoryMXBean = run {
    ManagementFactory.newPlatformMXBeanProxy(
            this.mBeanServerConnection,
            "java.lang:type=Memory",
            MemoryMXBean::class.java)
}

fun JMXConnector.rmxb(): RuntimeMXBean = run {
    ManagementFactory.newPlatformMXBeanProxy(
            this.mBeanServerConnection,
            "java.lang:type=Runtime",
            RuntimeMXBean::class.java)
}
